<?php

/**
 * 数据操作
 *
 * php /path/aishang/index.php top auto
 *
 * @author 
 */
if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}
include_once APPPATH . "libraries/ExceptionHandler.php";
include_once APPPATH . "core/base_controller.php";

class b2c extends base_controller {

    var $taobaoclient = null;

    public function __construct() {
        parent::__construct();
        $this->load->model('authorizetokenmodel'); //授权表
        $this->load->model('pushsettingmodel');

        $this->load->model('ordermodel', 'apachorder');
        $this->load->model('detailmodel', 'apachdetail');
        $this->load->library('ApachSdk');
        $this->load->library('queue', array('key' => 'bc2_queue')); //队列
    }

    /*
     *  拉取订单消息
     *  add by tongxiaoyong     
     */

    public function IncreOrder() {
        set_time_limit(0);
        $page = 1;
        $totalpages = 0;
        $startTime = date("Y-m-d H:i:s", strtotime('-100 day'));
        $endTime = date("Y-m-d H:i:s");
        try {
            //程序已在运行中即退出
            $running_log = APPPATH . "logs/B2cIncreOrder.run.lock";
            if (file_exists($running_log)) {
                return;
            }
            //创建运行锁
            file_put_contents($running_log, '1');

            //记录读取时间
            $log_last_run_file = APPPATH . "logs/b2cruntime.log";
            if (file_exists($log_last_run_file)) {
                $text = file_get_contents($log_last_run_file);
                $t = unserialize($text);
                if (isset($t['endTime'])) {
                    $diff_time = time() - strtotime($t['endTime']);
                    if ($diff_time > 5184000) {
                        $t['endTime'] = date("Y-m-d", strtotime("-60 day")) . " 23:59:59";
                    }
                    $startTime = $t['endTime'];
                    $endTime = date('Y-m-d H:i:s');
                }
            }

            //按时间分页读取数据
            $output = '';
            do {
                if (!isset($this->HJClient) || !$this->HJClient) {
                    $this->HJClient = new HJClient();
                }
                $orderModel = new OrderBCAPI(array($this->HJClient));
                $rs = $orderModel->search(array(
                    'min_modifyed' => $startTime,
                    'max_modifyed' => $endTime,
                    'status' => 1,
                    'page' => $page
                ));

                if (isset($rs['results']) && $rs['results']) {
                    $odata = $rs['results'];
                    $ototal = $rs['count'];
                    foreach ($odata as $v) {
                        if ($v['order_no']) {
                            $seristr = serialize(array('order_id' => $v['order_no'], 'user_id' => authorizetokenmodel::B2C_USER_ID));
                            $this->queue->push($seristr);
                            $output.=$seristr . "\n";
                        }
                    }
                    $totalpages = ceil($ototal / 10); //默认pagesize是10
                    //记录拉取时间
                    if ($output) {
                        echo "当前页数" . $page . "\n";
                        echo "modify->start:" . $startTime . '---' . $endTime . "|" . $page . "\n";
                        echo $output;
                        file_put_contents($log_last_run_file, serialize(array('startTime' => $startTime, 'endTime' => $endTime)));
                        echo "modify->end \n";
                    }
                }
                $page++;
            } while (($page - 1) < $totalpages);
            unset($this->HJClient);
            sleep(5);
        } catch (Exception $e) {
            echo 'Caught exception: ', $e->getMessage(), "\n";
        }
        unlink($running_log);
        echo "unlink log \n";
    }

    /*
     *  消费队列订单消息
     *  add by tongxiaoyong     
     */

    public function consumption() {
        set_time_limit(0);
        while (true) {
            try {
                $str = $this->queue->pop();
                $nowtime = time();
                $queue = unserialize($str);
                
                if (!$queue || !isset($queue['order_id']) || !isset($queue['user_id'])) {
                    continue;
                }
                //监测数据库连接状态
                if (@mysqli_ping($this->db->conn_id) === False) {
                    echo "heart gone away\n";
                    $this->db->reconnect();
                    $this->db->initialize();
                }
                if (!isset($this->HJClient) || !$this->HJClient) {
                    $this->HJClient = new HJClient();
                }
                $orderModel = new OrderBCAPI(array($this->HJClient));
                $tradeFullInfo = $orderModel->getOrderByTid($queue['order_id']);
                if ($tradeFullInfo) {
                    $this->db->trans_start();
                    $this->apachorder->newHjOrderInfo($queue['user_id'], $tradeFullInfo);
                    $this->apachdetail->newHjItemInfo($tradeFullInfo['order_no'], $tradeFullInfo['skus']);
                    $this->db->trans_complete();
                }
            } catch (Exception $e) {
                $this->queue->push($str);
            }
            usleep(100000);
        }
    }

}
